package com.proj.hot.fragment;

import android.content.Intent;
import android.content.res.AssetFileDescriptor;
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.Nullable;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.SurfaceHolder;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.proj.hot.GlobalParams;
import com.proj.hot.R;
import com.proj.hot.activity.LaunchActivity;
import com.proj.hot.activity.MinVideoView;
import com.proj.hot.activity.VODBuyPlayActivity;
import com.proj.hot.activity.webview.WebMainActivity;
import com.proj.hot.utils.DebugUtil;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.xutils.http.RequestParams;
import org.xutils.x;

import java.util.ArrayList;
import java.util.List;

/**
 * 推荐
 * Created by zangchenggang on 17/6/30.
 */
public class RecFragment extends BaseFragment implements MediaPlayer.OnPreparedListener, MediaPlayer.OnBufferingUpdateListener, MediaPlayer.OnCompletionListener,
        MediaPlayer.OnErrorListener, MediaPlayer.OnInfoListener {

    private List<View> viewList = new ArrayList<>();
    private View rec_view1, rec_view2, rec_view3, rec_view4, rec_view5, rec_view6, rec_view7, rec_view8;
    private ImageView rec_poster1, rec_poster2, rec_poster3, rec_poster4, rec_poster5, rec_poster6, rec_poster7, rec_poster8;
    private TextView text2, text3, text4, text5, text6, text7, text8;
    JSONArray dataArray;
    String code;


    List<String> mVideoUrl;
    MediaPlayer mPlayer;
    MinVideoView mVideoView;
    SurfaceHolder mSurfaceHolder;
    ImageView playerface;
    int mLastPosition = -1;
    //播放控制相关
    RelativeLayout mVideoViewParentLayout;
    int playIndex = 0;


    Button button1;
    private Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            if (msg.what == 0) {
                setView();

            }
            if (msg.what == 1) {
                if (null != mPlayer && mPlayer.isPlaying()) {
                    playerface.setVisibility(View.INVISIBLE);
                    DebugUtil.i("minPlayer", "MediaPlayer-蓝图消失------");
                }
            }
        }
    };


    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        if (code != null) {
            getData();
        }
    }

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {

        View rootView = inflater.inflate(R.layout.fragment_rec, container, false);
        rec_view1 = rootView.findViewById(R.id.rec_rl_poster1);
        rec_view2 = rootView.findViewById(R.id.rec_rl_poster2);
        rec_view3 = rootView.findViewById(R.id.rec_rl_poster3);
        rec_view4 = rootView.findViewById(R.id.rec_rl_poster4);
        rec_view5 = rootView.findViewById(R.id.rec_rl_poster5);
        rec_view6 = rootView.findViewById(R.id.rec_rl_poster6);
        rec_view7 = rootView.findViewById(R.id.rec_rl_poster7);
        rec_view8 = rootView.findViewById(R.id.rec_rl_poster8);

        viewList.add(rec_view1);
        viewList.add(rec_view2);
        viewList.add(rec_view3);
        viewList.add(rec_view4);
        viewList.add(rec_view5);
        viewList.add(rec_view6);
        viewList.add(rec_view7);
        viewList.add(rec_view8);
        rec_view2.requestFocus();
        setOnListener();

        rec_poster1 = (ImageView) rootView.findViewById(R.id.rec_poster1);
        rec_poster2 = (ImageView) rootView.findViewById(R.id.rec_poster2);
        rec_poster3 = (ImageView) rootView.findViewById(R.id.rec_poster3);
        rec_poster4 = (ImageView) rootView.findViewById(R.id.rec_poster4);
        rec_poster5 = (ImageView) rootView.findViewById(R.id.rec_poster5);
        rec_poster6 = (ImageView) rootView.findViewById(R.id.rec_poster6);
        rec_poster7 = (ImageView) rootView.findViewById(R.id.rec_poster7);
        rec_poster8 = (ImageView) rootView.findViewById(R.id.rec_poster8);

        text2 = (TextView) rootView.findViewById(R.id.rec_text2);
        text3 = (TextView) rootView.findViewById(R.id.rec_text3);
        text4 = (TextView) rootView.findViewById(R.id.rec_text4);
        text5 = (TextView) rootView.findViewById(R.id.rec_text5);
        text6 = (TextView) rootView.findViewById(R.id.rec_text6);
        text7 = (TextView) rootView.findViewById(R.id.rec_text7);
        text8 = (TextView) rootView.findViewById(R.id.rec_text8);

        //button1 = (Button)rootView.findViewById(R.id.launch_btn1);
        //setooo();
        mVideoUrl = new ArrayList<String>();

//播放窗口
        mVideoViewParentLayout = (RelativeLayout) rootView.findViewById(R.id.vod_player_view_parent);
        playerface = (ImageView) rootView.findViewById(R.id.playerface);


        return rootView;
    }


    void setPlayerView() {

        RelativeLayout.LayoutParams videoViewParams = new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.MATCH_PARENT, RelativeLayout.LayoutParams.MATCH_PARENT);
        videoViewParams.addRule(RelativeLayout.CENTER_IN_PARENT, RelativeLayout.TRUE);
        mVideoView = new MinVideoView(getContext());
        mVideoView.setLayoutParams(videoViewParams);
        mVideoViewParentLayout.addView(mVideoView, 0);

        mSurfaceHolder = mVideoView.getHolder();
        mSurfaceHolder.addCallback(new SurfaceHolder.Callback() {
            @Override
            public void surfaceCreated(SurfaceHolder holder) {
                if (mPlayer == null) {

                    try{
                        AssetFileDescriptor afd = getActivity().getResources().openRawResourceFd(R.raw.videoviewdemo);//获取raw下的视频文件  ;

                        mPlayer = new MediaPlayer();
                        mPlayer.setLooping(true);
                        mPlayer.setScreenOnWhilePlaying(true);
                        mPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
                        mPlayer.setDisplay(holder);
                        mPlayer.setOnPreparedListener(RecFragment.this);
                        mPlayer.setOnBufferingUpdateListener(RecFragment.this);
                        mPlayer.setOnCompletionListener(RecFragment.this);
                        mPlayer.setOnErrorListener(RecFragment.this);
                        mPlayer.setOnInfoListener(RecFragment.this);

                        mPlayer.setDataSource(/*"/sdcard/ceshi.mp4"*/afd.getFileDescriptor(), afd.getStartOffset(), afd.getLength());
                        DebugUtil.i("minPlayer", "MediaPlayer-初始化------");


                    }catch (Exception e){

                    }

                }
            }

            @Override
            public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) {
                if (mPlayer != null) {
                    mPlayer.setDisplay(holder);
                    if (!mPlayer.isPlaying() && ((LaunchActivity) getActivity()).viewPager.getCurrentItem() == 0) {
                        startupPlay();
                    }
                }
            }

            @Override
            public void surfaceDestroyed(SurfaceHolder holder) {
            }
        });
    }


    @Override
    public void onPause() {
        super.onPause();

        if (mPlayer != null) {
            if (mPlayer.isPlaying()) {
                mPlayer.pause();
            }

            if(GlobalParams.viewpageCur == 0){

                //---2018
                releaseMediaPlayer();
            }

            playIndex = 0;
            playerface.setVisibility(View.VISIBLE);
        }
    }


    @Override
    public void onResume() {
        super.onResume();
//注释掉的很容易出现空指针
//        if (((LaunchActivity) getActivity()).viewPager.getCurrentItem() == 0) {
//            if (mPlayer != null) {
//                if (!mPlayer.isPlaying()) {
//                    mPlayer.start();
//                }
//            }
//        }

        playerface.setVisibility(View.GONE);
        if( GlobalParams.viewpageCur == 0){
            if (mPlayer != null) {
                if (!mPlayer.isPlaying()) {
                    mPlayer.start();

                }
            }else{

                DebugUtil.i("minPlayer", "回来-------");

            }
        }else{
            if (mPlayer != null) {

                mPlayer.pause();

            }
        }


    }

    public void isOnShow(int index) {
        if (index == 0) {
            if (mPlayer != null) {
                if (!mPlayer.isPlaying()) {
                    mPlayer.start();
                    handler.sendEmptyMessageDelayed(1, 500);
                }
            }else{

            }
        } else {
            if (mPlayer != null) {
                if (mPlayer.isPlaying()) {
                    mPlayer.pause();
                    playerface.setVisibility(View.VISIBLE);
                }
            }
        }


    }

    private void setooo(){
        rec_view1.setOnFocusChangeListener(new View.OnFocusChangeListener() {
            @Override
            public void onFocusChange(View view, boolean b) {
                if(b){
                    button1.setBackgroundResource(R.drawable.kan_xz);
                }
            }
        });
        rec_view2.setOnFocusChangeListener(new View.OnFocusChangeListener() {
            @Override
            public void onFocusChange(View view, boolean b) {
                if(b){
                    button1.setBackgroundResource(R.drawable.kan_xz);
                }
            }
        });
        rec_view3.setOnFocusChangeListener(new View.OnFocusChangeListener() {
            @Override
            public void onFocusChange(View view, boolean b) {
                if(b){
                    button1.setBackgroundResource(R.drawable.kan_xz);
                }
            }
        });
        rec_view4.setOnFocusChangeListener(new View.OnFocusChangeListener() {
            @Override
            public void onFocusChange(View view, boolean b) {
                if(b){
                    button1.setBackgroundResource(R.drawable.kan_xz);
                }
            }
        });
        rec_view5.setOnFocusChangeListener(new View.OnFocusChangeListener() {
            @Override
            public void onFocusChange(View view, boolean b) {
                if(b){
                    button1.setBackgroundResource(R.drawable.kan_xz);
                }
            }
        });

    }

    private void setOnListener() {




        for (int i = 0; i < viewList.size(); i++) {
            final int k = i;
            viewList.get(i).setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {

                    if (k == 0) {
//                        ((LaunchActivity) getActivity()).viewPager.setCurrentItem(1);
                        //((LaunchActivity)getActivity()).movieFocusView.setVisibility(View.VISIBLE);
//                        ((LaunchActivity) getActivity()).movieFocus = 1;
                        //((LaunchActivity)getActivity()).movieFocusView.bringToFront();
                        GlobalParams.viewpageCur = 1;
                        if (mPlayer != null) {
                            if (mPlayer.isPlaying()) {
                                mPlayer.pause();
                            }


                            GlobalParams.playCurrentPosition=mPlayer.getCurrentPosition();

                        }

//                        new Handler().postDelayed(new Runnable() {
//                            @Override
//                            public void run() {
//                                ((LaunchActivity) getActivity()).movieFocusView.setVisibility(View.VISIBLE);
//                                ((LaunchActivity) getActivity()).movieFocusView.bringToFront();
//                            }
//                        }, 550);


                        Intent intent = new Intent(getActivity().getApplicationContext(), VODBuyPlayActivity.class);
                        try {
                            intent.putExtra("contentid", dataArray.getJSONObject(k).getString("recode"));
                            intent.putExtra("goodsORtrave", "goods");
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                        startActivity(intent);
                        releaseMediaPlayer();
                        playIndex = 0;
                        playerface.setVisibility(View.VISIBLE);



                    }else{


                        String url="";


//                        活动信息=》page/1.0.5.html?type=hdxx&code=fntv_xfzf_hdxx
//                        以案释法=》page/1.0.5.html?type=yasf&code=fntv_xfzf_yasf
//                        法律法规库=》page/1.0.5.html?type=flfgk&code=fntv_xfzf_flfgk
//                        法律服务案例库=》page/1.0.8.html?code=fntv_xfzf_flfwalk





                        if(k==1){

                            url=GlobalParams.HTML_PATH+"page/1.0.5.html?type=hdxx&code=fntv_xfzf_hdxx";
                        }

                        if(k==2){

                            url=GlobalParams.HTML_PATH+"page/1.0.5.html?type=yasf&code=fntv_xfzf_yasf";
                        }
//                        http://43.255.229.110:9556/fntvol/htm/page/1.0.5.html?type=yasf&code=fntv_xfzf_yasf

                        if(k==3){

                            url=GlobalParams.HTML_PATH+"page/1.0.5.html?type=flfgk&code=fntv_xfzf_flfgk";
                        }


                        if(k==4){

                            url=GlobalParams.HTML_PATH+"page/1.0.8.html?code=fntv_xfzf_flfwalk";
                        }



                        Intent intent = new Intent(getActivity().getApplicationContext(), WebMainActivity.class);


                        intent.putExtra("weburl", url);

                        startActivity(intent);




                    }

                        // if jsonarray type=13




                }
            });
        }
    }


    public void setCodeAndInitData(String code) {

        this.code = code;

    }


    private void getData() {

        try {

            /**
             * ---------------body------------------
             */
            JSONObject body = new JSONObject();
            body.put("code", code);
            body.put("sn", GlobalParams.SN);

            RequestParams params = new RequestParams(GlobalParams.reqHost + "featuredFirst/getDetails?" + code);
            params.setAsJsonContent(true);
            params.setBodyContent(body.toString().trim());

            /**
             * ---------------send------------------
             */
            x.http().post(params, new org.xutils.common.Callback.CommonCallback<String>() {
                @Override
                public void onSuccess(String s) {
                    DebugUtil.i("recf", "s=" + s);
                    try {
                        JSONObject jData = new JSONObject(s);

                        JSONObject respbody = jData.getJSONObject("respbody");
                        dataArray = respbody.getJSONArray("data");
                        handler.sendEmptyMessage(0);

                    } catch (Exception e) {
                        e.printStackTrace();
                    }

                }

                @Override
                public void onFinished() {

                }

                @Override
                public void onCancelled(CancelledException e) {

                }

                @Override
                public void onError(Throwable throwable, boolean b) {

                }
            });


        } catch (Exception e) {
            e.printStackTrace();
        }


    }


    private void getDataUrl(String urlcode) {

        try {

            /**
             * ---------------body------------------
             */
            JSONObject body = new JSONObject();
            body.put("code", urlcode);
            DebugUtil.i("playurl", "code：" + urlcode);
            body.put("sn", GlobalParams.SN);
            RequestParams params = new RequestParams(GlobalParams.reqHost + "column/getDetails?" + urlcode);
            DebugUtil.i("playurl", "请求地址:" + GlobalParams.reqHost + "column/getDetails?" + urlcode);
            params.setAsJsonContent(true);
            params.setBodyContent(body.toString().trim());

            /**
             * ---------------send------------------
             */
            x.http().post(params, new org.xutils.common.Callback.CommonCallback<String>() {
                @Override
                public void onSuccess(String s) {
                    try {
                        DebugUtil.i("playurl", "获取小窗口播放串：" + s);
                        JSONObject jData = new JSONObject(s);


                        JSONObject respbody = jData.getJSONObject("respbody");
                        JSONArray urlArray = respbody.getJSONArray("data");

                        for (int i = 0; i < urlArray.length(); i++) {
                            mVideoUrl.add(urlArray.getJSONObject(i).getString("playurl"));
                        }

                        setPlayerView();
                        if (mVideoUrl.size() > 0) {
                            handler.sendEmptyMessageDelayed(1, 500);
                        }

                    } catch (Exception e) {
                        e.printStackTrace();
                    }

                }

                @Override
                public void onFinished() {

                }

                @Override
                public void onCancelled(CancelledException e) {

                }

                @Override
                public void onError(Throwable throwable, boolean b) {

                }
            });


        } catch (Exception e) {
            e.printStackTrace();
        }


    }


    void setView() {

        try {
//            ImageLoader.getInstance().displayImage(dataArray.getJSONObject(0).getString("logo"),rec_poster1);
//            ImageLoader.getInstance().displayImage(dataArray.getJSONObject(1).getString("logo"), rec_poster2);
//            ImageLoader.getInstance().displayImage(dataArray.getJSONObject(2).getString("logo"), rec_poster3);
//            ImageLoader.getInstance().displayImage(dataArray.getJSONObject(3).getString("logo"), rec_poster4);
//            ImageLoader.getInstance().displayImage(dataArray.getJSONObject(4).getString("logo"), rec_poster5);
//            ImageLoader.getInstance().displayImage(dataArray.getJSONObject(5).getString("logo"), rec_poster6);
//            ImageLoader.getInstance().displayImage(dataArray.getJSONObject(6).getString("logo"), rec_poster7);
//            ImageLoader.getInstance().displayImage(dataArray.getJSONObject(7).getString("logo"), rec_poster8);


            if (GlobalParams.screenHeight == 1080) {//1920*1080 dpi=160
                text2.setTextSize(18);
                text3.setTextSize(18);
                text4.setTextSize(18);
                text5.setTextSize(18);
                text6.setTextSize(18);
                text7.setTextSize(18);
                text8.setTextSize(18);

            }

            text2.setText("");
            text3.setText("");
            text4.setText("");
            text5.setText("");
            text6.setText("");
            text7.setText("");
            text8.setText("");
            text2.setVisibility(View.GONE);
            text3.setVisibility(View.GONE);
            text4.setVisibility(View.GONE);
            text5.setVisibility(View.GONE);
            text6.setVisibility(View.GONE);
            text7.setVisibility(View.GONE);
            text8.setVisibility(View.GONE);

            getDataUrl(dataArray.getJSONObject(0).getString("recode"));
            DebugUtil.i("playurl", "recode=" + dataArray.getJSONObject(0).getString("recode"));
        } catch (JSONException e) {
            e.printStackTrace();
        }


    }


    private void startupPlay() {
        if (mVideoUrl == null || mPlayer.isPlaying())
            return;


        try {
            if (playIndex >= mVideoUrl.size()) {
                playIndex = 0;
            }

//            AssetManager assetManager=getContext().getAssets();
//
//
////            assetManager = getAssets();
////            AssetFileDescriptor fileDescriptor = assetManager.openFd("vdo/videoviewdemo.mp4");
////            mPlayer.setDataSource(fileDescriptor.getFileDescriptor(),fileDescriptor.getStartOffset(),
////                    fileDescriptor.getStartOffset());
////
////
////
////
//////            mPlayer.setDataSource(mVideoUrl.get(playIndex));
//
//            mPlayer.setDataSource(getContext(), Uri.parse("file:///android_asset/vdo/videoviewdemo.mp4"));
            mPlayer.prepareAsync();


            playIndex++;
            DebugUtil.i("minPlayer", "MediaPlayer-加载url------");

        } catch (IllegalArgumentException e) {
            e.printStackTrace();
        } catch (SecurityException e) {
            e.printStackTrace();
        } catch (IllegalStateException e) {
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


    /**
     * MediaPlayer.OnPreparedListener
     */
    @Override
    public void onPrepared(MediaPlayer mp) {

        mPlayer.start();
        mPlayer.seekTo(GlobalParams.playCurrentPosition);
//        playbtn.setImageResource(R.drawable.ic_stop);
    }

    /**
     * MediaPlayer.OnBufferingUpdateListener
     */
    @Override
    public void onBufferingUpdate(MediaPlayer mp, int percent) {
//        Log.v(TAG, "buffering process: " + percent);

//        String format = "缓冲中...(%1$d％)";
//        mBufferingHint.setText(String.format(format, percent));
//

        DebugUtil.i("minPlayer", "MediaPlayer-加载------"+ percent);

        if (mPlayer.getCurrentPosition() > 0 && playerface.getVisibility() == View.VISIBLE) {
            handler.sendEmptyMessageDelayed(1, 1000);
        }
    }

    /**
     * MediaPlayer.OnCompletionListener
     */
    @Override
    public void onCompletion(MediaPlayer mp) {
        //TODO
//        mPlayer.stop();
//        mPlayer.reset();
//        mLastPosition = 0;
//        startupPlay();
    }


    /**
     * MediaPlayer.OnInfoListener
     */
    @Override
    public boolean onInfo(MediaPlayer mp, int what, int extra) {
        // TODO Auto-generated method stub
        Log.i("VODPlayer", "snm_onInfo=" + what);
        switch (what) {
            case MediaPlayer.MEDIA_INFO_BUFFERING_END:
            case MediaPlayer.MEDIA_INFO_VIDEO_RENDERING_START:
//                mBufferingPage.setVisibility(View.INVISIBLE);
//                showControlPane();
                break;
            default:
                Log.i("VODPlayer", "执行了onInfo,并且抛出了(" + what + ")状态码!");
        }
        return false;
    }

    /**
     * r
     * MediaPlayer.OnErrorListener
     */
    @Override
    public boolean onError(MediaPlayer mp, int what, int extra) {
        // TODO Auto-generated method stub
        Log.i("VODPlayer", "snm_onError=" + what);
        switch (what) {
            case 54000:

                break;

            default:
                Log.i("VODPlayer", "执行了onError,并且抛出了(" + what + ")错误码!");
        }

//
        return false;
    }


    private void releaseMediaPlayer() {

        try {
            if (mPlayer != null) {
                /*if(mPlayer.isPlaying()) {
                    mPlayer.stop();
                }*/
                mPlayer.pause();
                mPlayer.stop();
                mPlayer.reset();
                mPlayer.release();
                mPlayer = null;


            }
        } catch (java.lang.IllegalStateException e) {
            e.printStackTrace();
        }


    }


}






